package com.yl.ydk.ui.activity

import android.content.Intent
import android.content.IntentFilter
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.yl.ydk.R
import com.yl.ydk.base.BaseActivity
import com.yl.ydk.base.BaseEvenBus
import com.yl.ydk.bean.WifiListBean
import com.yl.ydk.receiver.WifiBroadcastReceiver
import com.yl.ydk.ui.adapter.WifiInfoAdapter
import com.yl.ydk.utils.DialogUtils
import com.yl.ydk.utils.MyWifiManager
import com.yl.ydk.utils.Permission
import com.yl.ydk.utils.WifiUtils
import com.blankj.utilcode.utils.NetworkUtils
import com.blankj.utilcode.utils.ToastUtils
import kotlinx.android.synthetic.main.activity_wifi_setting.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

class WifiSettingActivity : BaseActivity(), WifiInfoAdapter.onListItemClick {

    private var mWifiManager: WifiManager? = null
    private var mScanResultList: List<ScanResult>? = null
    private val wifiListBeanList = mutableListOf<WifiListBean>()
    private var wifiAdapter: WifiInfoAdapter? = null
    private var wifiReceiver: WifiBroadcastReceiver? = null
    private var connextStart = false

    override fun getLayoutId(): Int = R.layout.activity_wifi_setting

    override fun attachView() {

    }

    override fun detachView() {

    }

    override fun initView() {
        Permission.requestPermission(this)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        if (mWifiManager == null) {
            mWifiManager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
        }
        //开启wifi
        MyWifiManager.openWifi(mWifiManager)
        swWifi.isChecked = true
        scanWifiList()
        swWifi.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                mWifiManager?.isWifiEnabled = true
                swWifi.isChecked = true
                scanWifiList()
            } else {
                rvWifi.visibility = View.GONE
                mWifiManager?.isWifiEnabled = false
                swWifi.isChecked = false
            }
        }
        if(NetworkUtils.isWifiConnected()){
            startActivityIn(Intent(this, BindingPhoneActivity::class.java), this)
            finish()
        }
    }

    private fun scanWifiList() {
        //获取到wifi列表
        rvWifi.visibility = View.VISIBLE
        mScanResultList = MyWifiManager.getWifiList(mWifiManager)
        mScanResultList?.forEach {
            val wifiListBean = WifiListBean(it.SSID, MyWifiManager.getEncrypt(mWifiManager, it))
            wifiListBeanList.add(wifiListBean)
        }
        if (wifiListBeanList.size > 0) {
            wifiAdapter = WifiInfoAdapter(wifiListBeanList)
            rvWifi.adapter = wifiAdapter
            val manager = LinearLayoutManager(this)
            manager.orientation = LinearLayoutManager.VERTICAL
            rvWifi.layoutManager = manager
            wifiAdapter?.onListItemClick(this)
            registerReceiverWifi()
        }
    }

    //监听wifi变化
    private fun registerReceiverWifi() {
        wifiReceiver = WifiBroadcastReceiver()
        val filter = IntentFilter()
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION) //监听wifi是开关变化的状态
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION) //监听wifi连接状态
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) //监听wifi列表变化（开启一个热点或者关闭一个热点）
        registerReceiver(wifiReceiver, filter)
    }

    @Subscribe
    fun evenbusMessage(baseEvenBus: BaseEvenBus) {
        when (baseEvenBus.messageId) {
            BaseEvenBus.CONNECTING -> {
                connextStart = true
            }
            BaseEvenBus.CONNECTED -> {  //wifi已连接
                if (connextStart) {
                    connextStart = false
                    DialogUtils.hideDialog()
                    ToastUtils.showLongToastSafe("连接成功.... ")
                    startActivityIn(Intent(this, BindingPhoneActivity::class.java), this)
                    finish()
                }
            }
            BaseEvenBus.DISCONNECTED -> {  //wifi没连接上
                if (connextStart) {
                    DialogUtils.hideDialog()
                    DialogUtils.showConnectFailDialog(this)
//                    ToastUtils.showLongToastSafe("密码错误.... ")
                    connextStart = false
                }
            }
        }
    }

    /**
     *  点击 WifiInfoAdapter Item
     */
    override fun onListItemClick(item: WifiListBean?) {
        DialogUtils.showCustomizeDialog(this, item, object : DialogUtils.OnWifiBtnOkListener {
            override fun OnWifiBtnOkListener(item: String?, wifiListBean: WifiListBean?) {
                MyWifiManager.disconnectNetwork(mWifiManager)  //断开当前wifi
                WifiUtils.connect(this@WifiSettingActivity, wifiListBean?.SSID, item)
                DialogUtils.showConnectingDialog(this@WifiSettingActivity)
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()  //取消监听
        wifiReceiver?.let {
            unregisterReceiver(it)
        }

    }

}